package com.sniff.atp.manage;

import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.utils.Headers;
import com.sniff.atp.utils.HttpClientUtil;
import com.sniff.atp.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class XXLManage {

    @Value("${sniff.xxl.host}")
    private String xxlHost;

    @Value("${sniff.xxl.username}")
    private String username;

    @Value("${sniff.xxl.password}")
    private String password;

    private String cookie;

    private void login() {
        String url = xxlHost + "/xxl-job-admin/login";
        JSONObject params = new JSONObject();
        params.put("userName", username);
        params.put("password", password);
        HttpClientUtil http = new HttpClientUtil();
        http.doPost(url, params);
        cookie = http.getRespHeader().get("Set-Cookie").split(";")[0];
    }

    private String pageList(String jobGroup, String jobDesc) {
        String url = xxlHost + "/xxl-job-admin/jobinfo/pageList";
        JSONObject params = new JSONObject();
        params.put("jobDesc", jobDesc);
        params.put("jobGroup", jobGroup);
        params.put("triggerStatus", "-1");
        params.put("start", 0);
        params.put("length", 10);
        String result = new HttpClientUtil(Headers.setXXLHeader(cookie)).doPost(url, params);
        return JsonUtil.extractString(result, "data[0].id");
    }

    public void runTask(String id) {
        login();
        String url = xxlHost + "/xxl-job-admin/jobinfo/trigger";
        JSONObject params = new JSONObject();
        params.put("id", id);
        new HttpClientUtil(Headers.setXXLHeader(cookie)).doPost(url, params);
    }
}
